<?php
/**
 * SmsService.php
 * 文件描述 短信消息服务类
 * Created on 2020/9/4 9:15
 * Created by 刘小龙 595929049@qq.com
 */

namespace app\common\services;


use AlibabaCloud\Client\AlibabaCloud;
use app\common\helpers\Response;

class SmsService
{
    private $gateway = 'aliyun';

    public function __construct()
    {
        $this->gateway = config('sms.default.gateway');
    }
    private function configAliClient()
    {
        $config = config('sms.gateways.aliyun');
        AlibabaCloud::accessKeyClient($config['access_key_id'], $config['access_key_secret'])
        ->regionId($config['region_id'])
        ->asDefaultClient();
        return $this;
    }

    public function sendVerifyCode(string $phone, string $code)
    {
        switch ($this->gateway){
            case 'aliyun': {
                $option = [
                    'query' => [
                        'PhoneNumbers'  => $phone,
                        'SignName'      => config('sms.gateways.aliyun.sign_name'),
                        'TemplateCode'  => config('sms.gateways.aliyun.templates.verify_code'),
                        'TemplateParam' => json_encode(['code' => $code])
                    ]
                ];
            }
        }
        return $this->sendSms($option);
    }

    /**
     * @todo 发送短信入口方法：根据不同网关选择不同服务商
     * @param array $option 短信配置
     * @return \AlibabaCloud\Client\Result\Result
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    private function sendSms(array $option)
    {
        // 根据不同网关选择不同服务商
        switch ($this->gateway) {
            case 'aliyun': {
                return $this->configAliClient()->sendAliSms($option);
            }
            default: return $this->sendAliSms($option);
        }
    }

    /**
     * @todo 发送阿里短信
     * @param array $option 短信内容配置信息
     * @return \AlibabaCloud\Client\Result\Result
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    private function sendAliSms(array $option)
    {
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options($option)
                ->request();
            if ($result->Code != 'OK'){
                throw new \think\Exception($result->Message, Response::HTTP_BAD_GATEWAY);
            }
            return true;
        } catch (\Exception $exception){
            throw new \think\Exception($exception->getMessage(), Response::HTTP_SERVICE_UNAVAILABLE);
        }
    }
}
